package streamAPI.project.easy;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author yue.cao
 * @since 09-29-2020
 */
public class DemoSocketWordCount {

	public static void main(String[] args) throws Exception {
		StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
		ParameterTool parameterTool = ParameterTool.fromArgs(args);
		DataStreamSource<String> source = env.socketTextStream(parameterTool.get("ip"), parameterTool.getInt("port"));

		source.flatMap(new FlatMapFunction<String, Tuple2<String,Integer>>() {
			@Override
			public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
				String[] split = value.toLowerCase().split("\\W+");
				for (String word :split){
					out.collect(new Tuple2<>(word,1));
				}
			}
		}).keyBy(new KeySelector<Tuple2<String,Integer>, String>() {

			@Override
			public String getKey(Tuple2<String, Integer> value) throws Exception {
				return value.f0;
			}
		}).sum(1).print().setParallelism(1);

		env.execute(DemoSocketWordCount.class.getName());
	}
}
